package com.hangan.langchainspringstart.repository;

import cn.hutool.core.util.StrUtil;
import com.hangan.langchainspringstart.constant.Common;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 通过<code>Redis</code>来记录会话消息
 *
 * @author hang an
 * @since 2025/7/31
 */
@RequiredArgsConstructor
@Repository
public class RedisChatMemoryStore implements ChatMemoryStore {

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 根据会话id获取会话消息
     *
     * @param memoryId 会话id
     * @return 会话消息
     */
    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        String messageJson = stringRedisTemplate.opsForValue().get(String.format(Common.MEMORY_ID, memoryId.toString()));
        if (StrUtil.isNotEmpty(messageJson)) {
            return ChatMessageDeserializer.messagesFromJson(messageJson);
        }
        return List.of();
    }

    /**
     * 更新会话消息
     *
     * @param memoryId 会话id
     * @param list     会话消息
     */
    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        // 1.把list 转为json数据
        String messagesJson = ChatMessageSerializer.messagesToJson(list);
        // 2.保存到redis中
        stringRedisTemplate.opsForValue().set(String.format(Common.MEMORY_ID, memoryId.toString()),
                messagesJson, Common.DEFAULT_TIME_OUT, TimeUnit.DAYS);
    }

    /**
     * 删除会话消息
     * @param memoryId 会话id
     */
    @Override
    public void deleteMessages(Object memoryId) {
        stringRedisTemplate.delete(String.format(Common.MEMORY_ID, memoryId.toString()));
    }
}
